package cn.tianjindong.blog_portal.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.tianjindong.blog.common.utils.FastDFSClient;

@Controller
public class ImageUploadController {

	@Value("${tracker_server}")
	private String trackerServer;
	
	@Value("${nginx_path}")
	private String nginx_path;

	@RequestMapping("/upload.action")
	@ResponseBody
	public String imgUpload(@RequestParam("uploadFile") MultipartFile uploadFile) {
		// 获取文件名称
		String originalFilename = uploadFile.getOriginalFilename();
		// 获取文件后缀名
		String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
		Map<String, Object> map = new HashMap<String, Object>();
		// 生成FastDFS工具类对象
		try {
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/client.conf");
			// group1/M00/00/00/wKgZhVv1U-KAD-MTAAeqM-JCYpw762.jpg
			String result = fastDFSClient.uploadFile(uploadFile.getBytes(), suffix);

			// 获取配置文件中指定的图片服务器的地址，然后拼接该图片的URL
			String url = "http://" + nginx_path + "/" + result;
			List<String> list = new ArrayList<String>();
			list.add(url);

			map.put("errno", 0);
			map.put("data", list);

		} catch (Exception e) {
			e.printStackTrace();
			map.put("error", 1);
			map.put("message", "图片上传失败");
		}
		// 因为浏览器的兼容问题，我们没有直接返回Map对象让Spring帮我们转换成JSON
		String str = JSON.toJSONString(map);
		System.out.println(str);
		return str;
	}
}
